import React from 'react'
import $ from 'jquery'
import _ from 'underscore'

export default class DropdownList extends React.Component {

  constructor(props) {
    super(props);

    this.openMenu = this.openMenu.bind(this)
    this.closeMenu = this.closeMenu.bind(this)

    this.state = {
      open: false,
      defaultStyle:{
        display:'inline-block'
      }
    }
    this.state.current = this.props.current || this.props.list[0];
  }

  openMenu() {
    if(!this.props.disabled) {
      this.setState({open: true});
    }
  }

  selectHandler(item) {
    this.props.onChanging(item);
  }

  closeMenu(e) {
    if (this.state.open) {
      let el = e.target
        , container = this.refs.root;

      if (!$.contains(container,el)) {
        this.setState({open: false});
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.current) {
      this.setState({open: false, current: nextProps.current});
    } else {
      this.setState({open: false, current: this.state.current || this.props.list[0]});
    }
  }

  componentWillUnmount() {
    $('body').off('click', this.closeMenu);
  }

  componentDidMount() {
    $('body').on('click', this.closeMenu);
  }

  render() {
    return (
      <div className="dropdown" ref="root" style={_.extend({}, this.state.defaultStyle, this.props.style)}>
        <strong onClick={this.openMenu} className={!this.props.disabled ? '' : 'dropdown-forbidden'}>
          <span>{ !this.state.current.value ? this.props.defaultText : this.state.current.label }</span>
          <i className="iconfont icon-btn-arrow" style={{float:'right'}}>&#xe619;</i>
        </strong>
        <div
          className={this.props.leftAlign ? 'dropdown-main-left' : 'dropdown-main'}
          style={_.extend({display: (this.state.open ? 'block' : 'none')}, this.props.dropdownStyle)}>
          <ul>
            {
              this.props.list.map((item) => {
                return (<li key={'DropdownList-item-' + item.value} className="dropdown-item"><a onClick={this.selectHandler.bind(this, item)}>{item.label}</a></li>);
              })
            }
          </ul>
        </div>
      </div>
    )
  }
}

DropdownList.defaultProps = {
  style: {},
  dropdownStyle:{},
  onChanging: (item) => console.log('DropdownList.defaultProps.onChanging:', item),
  current: {},
  list: [], //{label: '7 天前', value: 7, other...}
  defaultText: '其它',
  leftAlign: true,
  disabled: false
}
